<?php

use app\common\model\Area;
use app\common\model\shop\Ordergoods;
use fast\Random;
use GuzzleHttp\Client;
use think\Env;
use think\Log;
use GuzzleHttp\Exception\ClientException;
use think\Cache;

class Hyc
{

    protected $openToken;
    protected $appKey = "atbc55qS";
    protected $appSecret = "B8649836FE2EFF3810501387C2CD7733";
    protected $bookid = "2625964587355596";
    protected $url = "https://openapi.chanjet.com";
    protected $certificate = "Jf+LmYUqM4F0mCc3pvFY8l9F4CW62PIIX5bMKnsrTPoPmitaNNAGUSoIcBeywC+ilstPZFRe+O+bRVQwCCOWdYIhHuVA2gPpSqW9Pwqecx61/6GQJUl7RvjkYtCFRsErDQYFqw4ykiRcydC5UL59AjbjKimtfZ5kUoPJ8JJZDRlPdSCk95c4WH7+0oXbyowO";
    function __construct($options = [])
    {
        $this->getToken();
    }


    private function getToken()
    {
        if (Cache::get('hyc_token')) {
            $this->openToken = Cache::get('hyc_token');
        } elseif (Cache::get('hyc_fre_token')) {
            $url = $this->url . "/auth/v2/refreshToken";
            $data = [
                "grantType" => "refresh_token", //Cache::get("hyc_ticket")
                "refreshToken" => Cache::get('hyc_fre_token'),
                // "productCategory" => [
                //     "code" => $goods->category->id,
                //     "name" => $goods->category->name,
                // ],
                // "productUomSetting" => [
                //     "baseUomName" => $goods->unit,
                // ]
                // 'bookid'=>$this->bookid,
            ];
            $client = new Client();
            try {
                $resp = $client->get($url, [
                    "headers" => [
                        // "openToken" => $this->openToken,
                        "appKey" => $this->appKey,
                        "appSecret" => $this->appSecret,
                        "content-type" => "application/json",
                    ],
                    'query' => $data
                ]);
                $res = $resp->getBody();
                $res = json_decode($res, 1);
                Log::error("addgoods请求结果" . var_export($res, 1));
                if ($res['code'] == 200) {
                    Cache::set('hyc_token', $res['result']['access_token'], $res['result']['expires_in'] - 10);
                    Cache::set('hyc_fre_token', $res['result']['refresh_token'], $res['result']['refresh_expires_in'] - 10);
                    $this->openToken = $res['result']['access_token'];
                } else {
                }
            } catch (ClientException $e) {

                // echo $e->getRequest();
                // echo $e->getResponse();
            }
        } else {
            $url = $this->url . "/v1/common/auth/selfBuiltApp/generateToken";
            $data = [
                "appTicket" => Cache::get("hyc_ticket"),
                "certificate" => $this->certificate,
                // "productCategory" => [
                //     "code" => $goods->category->id,
                //     "name" => $goods->category->name,
                // ],
                // "productUomSetting" => [
                //     "baseUomName" => $goods->unit,
                // ]
                // 'bookid'=>$this->bookid,
            ];
            $client = new Client();
            try {
                $resp = $client->post($url, [
                    "headers" => [
                        // "openToken" => $this->openToken,
                        "appKey" => $this->appKey,
                        "appSecret" => $this->appSecret,
                        // "content-type"=>"application/json",
                    ],
                    'json' => $data
                ]);
                $res = $resp->getBody();
                $res = json_decode($res, 1);
                Log::error("addgoods请求结果" . var_export($res, 1));
                if ($res['result'] == true) {
                    Cache::set('hyc_token', $res['value']['accessToken'], $res['value']['expiresIn'] - 10);
                    Cache::set('hyc_fre_token', $res['value']['refreshToken'], $res['value']['refreshExpiresIn'] - 10);
                    $this->openToken = $res['value']['accessToken'];
                } else {
                }
            } catch (ClientException $e) {

                // echo $e->getRequest();
                // echo $e->getResponse();
            }
        }
    }
    public function addGoods($goods)
    {
        $url =  $this->url . "/accounting/openapi/cc/product/add/{$this->bookid}";
        $data = [[
            "productCode" => 'goods_' . $goods->id,
            "productName" => '' . $goods->title,
            "productCategory" => [
                "code" => "00",
                "name" => '未分类',
            ],
            "productUomSetting" => [
                "baseUomName" => $goods->unit ? $goods->unit : '斤',
            ]
            // 'pageSize' => 10,
            // 'pageNo' => 1,

        ]];
        $client = new Client();
        try {
            $resp = $client->post($url, [
                "headers" => [
                    "openToken" => $this->openToken,
                    "appKey" => $this->appKey,
                    "appSecret" => $this->appSecret,
                    "content-type" => "application/json",
                ],
                'json' => $data
            ]);
            $res = $resp->getBody();
            $res = json_decode($res, 1);
            Log::error("addgoods请求结果" . var_export($res, 1));
            if ($res['success'] == true) {
                $goods->product_code = 'goods_' . $goods->id;
            } else {
                exception('好有财接口异常:' . $res['message']);
            }
        } catch (ClientException $e) {
            // echo $e->getRequest();
            $res = $e->getResponse()->getBody()->getContents();
            $res = json_decode($res, 1);
            if ($res) {
                exception('好有财异常' . ($res['message'] ?? '同步异常'));
            } else {
                exception('好有财异常');
            }
            // var_dump($e->getResponse()->getBody()->getContents());
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
    }

    public function syncGoods($goods)
    {
    }

    public function addOrder($order)
    {
        $url = $this->url . "/accounting/openapi/cc/salesorder/add/{$this->bookid}";
        $goodsItem = [];
        $ordergoods = Ordergoods::where('order_id', $order->id)->select();
        foreach ($ordergoods as $goods) {
            if (!empty($goods->goods_info_json['product_code'])) {
                array_push($goodsItem, [
                    'productCode' => $goods->goods_info_json['product_code'],
                    'warehouseCode' => '01',
                    'quantity' => $goods->total,
                    'unit' => $goods->goods_info_json['unit'] ? $goods->goods_info_json['unit'] : '袋',
                    'price' => $goods->price,
                    'amount' => $goods->price * $goods->total,
                ]);
            }
        }
        $address_arr = explode('/', $order->consign_address);
        $data = [
            "bizDate" => date('Y-m-d'),
            "code" => $order->order_no,
            // 'redBlueFlagEnum' => "BLUE",
            // "noteType" => "NO_INVOICE",
            "custVendorCode" => '000423456',
            "warehouseCode" => '01',
            "goodsItem" => $goodsItem,
            "salesOrderShipTo" => [
                // [
                "telephoneNum" => $order->consign_mobile,
                "attnName" => $order->consign_name,
                "country" => "中国",
                "province" => empty($address_arr[0]) ? '' : (Area::where('shortname|name', 'like', "{$address_arr[0]}%")->where('level', 1)->value('name') ?? ''),
                "city" => $address_arr[1] ?? '',
                "disctrict" => $address_arr[2] ?? '',
                "address1" => $address_arr[3] ?? ''
                // ]
            ],
            'Employee' => [
                'name' => $order->user->nickname ?? '',
                'mobile' => $order->user->mobile ?? '',
            ],
            'comments' => ($order->remark ?? ''),
            'customizedField' => [
                [
                    'name' => '配送方式',
                    'value' => $order->distribution->title ?? '',
                ],
                [
                    'name' => '总重量',
                    'value' => $order->total_weight ?? '',
                ],
                [
                    'name' => '配送费',
                    'value' => $order->send_fee ?? 0,
                ],
                [
                    'name' => '客户名称',
                    'value' => $order->custom['name'] ?? '',
                ],

            ]

            // 'bookid'=>$this->bookid,
        ];
        // var_dump($data);
        $client = new Client();
        try {
            $resp = $client->post($url, [
                "headers" => [
                    "openToken" => $this->openToken,
                    "appKey" => $this->appKey,
                    "appSecret" => $this->appSecret,
                    "content-type" => "application/json",
                ],
                'body' => json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)
            ]);
            $res = $resp->getBody();
            $res = json_decode($res, 1);
            if ($res['success'] == true) {
            } else {
                Log::error('好有财异常' . var_export($res, 1));

                exception('好有财接口异常:' . $res['message']);
            }
        } catch (ClientException $e) {
            // echo $e->getRequest();
            $res = $e->getResponse()->getBody()->getContents();
            $res = json_decode($res, 1);
            if ($res) {
                exception('好有财异常' . ($res['message'] ?? '同步异常'));
                Log::error('好有财异常' . var_export($res, 1));
            } else {
                Log::error('好有财异常' . var_export($e->getResponse(), 1));
                exception('好有财异常');
            }
            // var_dump($e->getResponse()->getBody()->getContents());
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
    }

    public function orderList()
    {
        $url = $this->url . "/accounting/openapi/cc/goodsissue/list/{$this->bookid}";

        $data = [
            // "bizDate" => date('Y-m-d'),
            // "code" => $order->order_no,
            // 'redBlueFlagEnum' => "BLUE",
            // "noteType" => "NO_INVOICE",
            // "custVendorCode" => '0001',
            // "warehouseCode" => '0001',
            // "goodsItem" => $goodsItem
            "page" => 1,
            "pageSize" => 10,
            // 'bookid'=>$this->bookid,
        ];
        $client = new Client();
        try {
            $resp = $client->post($url, [
                "headers" => [
                    "openToken" => $this->openToken,
                    "appKey" => $this->appKey,
                    "appSecret" => $this->appSecret,
                    // "content-type"=>"application/json",
                ],
                'json' => $data
            ]);
            $res = $resp->getBody();
            $res = json_decode($res, 1);
            var_dump($res);
            die;
            if ($res['success'] == true) {
            } else {
            }
        } catch (ClientException $e) {
            // echo $e->getRequest();
            var_dump($e->getResponse()->getBody()->getContents());
        }
    }

    function orderDetail($id)
    {
        $url = $this->url . "/accounting/openapi/cc/goodsissue/query/{$id}/{$this->bookid}";

        $data = [
            // "bizDate" => date('Y-m-d'),
            // "code" => $order->order_no,
            // 'redBlueFlagEnum' => "BLUE",
            // "noteType" => "NO_INVOICE",
            // "custVendorCode" => '0001',
            // "warehouseCode" => '0001',
            // "goodsItem" => $goodsItem
            "page" => 1,
            "pageSize" => 10,
            // 'bookid'=>$this->bookid,
        ];
        $client = new Client();
        try {
            $resp = $client->get($url, [
                "headers" => [
                    "openToken" => $this->openToken,
                    "appKey" => $this->appKey,
                    "appSecret" => $this->appSecret,
                    // "content-type"=>"application/json",
                ],
                // 'json' => $data
            ]);
            $res = $resp->getBody();
            $res = json_decode($res, 1);
            var_dump($res);
            die;
            if ($res['success'] == true) {
            } else {
            }
        } catch (ClientException $e) {
            // echo $e->getRequest();
            var_dump($e->getResponse()->getBody()->getContents());
        }
    }

    public function goodsList()
    {
        $url = $this->url . "/accounting/openapi/cc/product/list/{$this->bookid}";

        $data = [
            // "bizDate" => date('Y-m-d'),
            // "code" => $order->order_no,
            // 'redBlueFlagEnum' => "BLUE",
            // "noteType" => "NO_INVOICE",
            // "custVendorCode" => '0001',
            // "warehouseCode" => '0001',
            // "goodsItem" => $goodsItem
            // "code"=>'goods_143',
            "page" => 1,
            "pageSize" => 10,
            // 'bookid'=>$this->bookid,
        ];
        $client = new Client();
        try {
            $resp = $client->post($url, [
                "headers" => [
                    "openToken" => $this->openToken,
                    "appKey" => $this->appKey,
                    "appSecret" => $this->appSecret,
                    // "content-type"=>"application/json",
                ],
                'json' => $data
            ]);
            $res = $resp->getBody();
            $res = json_decode($res, 1);
            var_dump($res);
            die;
            if ($res['success'] == true) {
            } else {
            }
        } catch (ClientException $e) {
            // echo $e->getRequest();
            $res = $e->getResponse()->getBody()->getContents();
            $res = json_decode($res, 1);
            if ($res) {
                exception($res['message'] ?? '同步异常');
            } else {
                exception('接口异常');
            }
            // var_dump($e->getResponse()->getBody()->getContents());
        } catch (\Exception $e) {
            exception($e->getMessage());
        }
    }
}
